<template>
  <jke-modal
      :visible.sync="jkeForm.visible"
      :width="1200"
      :title="jkeForm.title"
      :fullscreen.sync="jkeForm.fullscreen"
      :switchFullscreen="jkeForm.switchFullscreen"
    >
    <!--  -->
    <crumbs
      @goBack="goBack"
      :superiorMenu="['技术管理', 'BOM信息']"
      marginBottom="10px"
      :currentMenu="pageTitle"
    ></crumbs>
    <div class="form-body">
      <a-card title="基本信息" :bordered="false">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="物料">
            <a-input placeholder="请选择" :disabled="isEdit" :read-only="true" :class="goodsName?'has-value':''" @click="showSelect" :value="goodsName">
              <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
              <a-icon slot="suffix" type="close-circle" theme="filled" class="close-icon" @click="getSelectValue(false, '', [])" />
            </a-input>
            <goodsTableSelect ref="goodsTableSelect" @getSelectValue="getSelectValue" :key="selectIndex">
            </goodsTableSelect>
          </a-form-item>
          <a-form-item label="规格">
            <a-input v-decorator="['spec']" placeholder="-" disabled />
          </a-form-item>
          <a-form-item label="基本单位">
            <a-input v-decorator="['basicUnitText']" placeholder="-" disabled />
          </a-form-item>
          <a-form-item label="物料类型">
            <a-input v-decorator="['typeText']" placeholder="-" disabled />
          </a-form-item>
          <a-form-item label="分类">
            <a-input v-decorator="['categoryText']" placeholder="-" disabled />
          </a-form-item>
          <div class="ant-form-item"></div>
        </a-form>
      </a-card>
      <a-card title="子物料" :bordered="false" style="margin-top: 12px">
        <j-editable-table
          ref="goodsTable"
          :loading="goodsTable.loading"
          :columns="goodsTable.columns"
          :dataSource="goodsTable.dataSource"
          :maxHeight="300"
          :rowNumber="true"
          :actionButton="true"
          @valueChange="valueChange"
        >
          <template v-slot:action="props">
            <a-popconfirm title="是否删除?" ok-text="是" cancel-text="否" @confirm="handleDeleteGood(props)">
              <span class="del-text">删除</span>
            </a-popconfirm>
          </template>
          <template v-slot:goodsId="props">
            <a-input placeholder="请选择" :read-only="true" @click="showBomSelect(props)" :value="BomNameText(props)" :class="BomNameText(props)?'has-value':''">
              <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
              <a-icon slot="suffix" type="close-circle" theme="filled" class="close-icon" @click="getSelectBomValue(false, '', [], props.rowId)" />
            </a-input>
          </template>
        </j-editable-table>
      </a-card>
      <a-card title="其他信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="备注" style="flex: 1">
            <a-textarea placeholder="请输入" :maxLength="500" auto-size v-decorator="['remark']" />
          </a-form-item>
        </a-form>
        <a-form layout="vertical">
          <a-form-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，每个大小不可超过20M</p>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
    <goodsTableSelect
      ref="bomTableSelect"
      @getSelectValue="getSelectBomValue"
      :key="selectIndex"
    >
    </goodsTableSelect>
    <div class="footer-submit form-footer">
      <a-button type="primary" :loading="loadingSubmit" @click="handleSubmit"> 提交 </a-button>
    </div>
  </jke-modal>
</template>
<script>
import crumbs from '@/components/crumbs.vue'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { API } from '@/api/requestFzs'
import moment from 'dayjs'
import JEditableTable from '@/components/jeecg/JEditableTable.vue'
import { validateTables, FormTypes, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { fourFloatNum } from '@/utils/util'
import goodsTableSelect from '@/components/goodsTableSelect'
export default {
  data() {
    return {
      jkeForm: {
        title: '新建BOM',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      attachment: '',
      pageTitle: '新建BOM',
      submitApi: API.messBomInfoAdd,
      isEdit: false,
      loadingSubmit: false,
      goodSelectList: [],
      goodsTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料',
            width: '26%',
            key: 'goodsId',
            type: FormTypes.slot,
            slotName: 'goodsId',
            placeholder: '请输入${title}',
            options: [],
            isrequired: true,
            allowSearch: true,
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '规格',
            width: '13%',
            key: 'spec',
            type: FormTypes.input,
            placeholder: '-',
            disabled: true,
            defaultValue: '',
          },
          {
            title: '物料类型',
            width: '13%',
            key: 'typeText',
            type: FormTypes.input,
            placeholder: '-',
            disabled: true,
            defaultValue: '',
          },
          {
            title: '基本单位',
            width: '13%',
            key: 'basicUnitText',
            type: FormTypes.input,
            placeholder: '-',
            disabled: true,
            defaultValue: '',
          },
          {
            title: 'goodsName',
            key: 'goodsName',
            type: FormTypes.hidden,
          },
          {
            title: 'goodsCode',
            key: 'goodsCode',
            type: FormTypes.hidden,
          },
          {
            title: '基础用量',
            width: '15%',
            key: 'basicUseLevel',
            type: FormTypes.inputNumber,
            isrequired: true,
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [
              { required: true, message: '${title}不能为空' },
              {
                pattern: /[1-9]+[0-9]*/,
                message: '${title}不能为空且必须大于0',
              },
            ],
          },
          {
            title: '损耗(%)',
            width: '15%',
            key: 'loss',
            type: FormTypes.inputNumber,
            isrequired: true,
            placeholder: '请输入${title}',
            defaultValue: '0',
            validateRules: [
              { required: true, message: '${title}不能为空' },
              // {
              //   pattern: /[1-9]+[0-9]*/,
              //   message: '${title}不能为空且必须大于0',
              // },
            ],
          },
          {
            title: '操作',
            width: '5%',
            key: 'action',
            type: FormTypes.slot,
            placeholder: '选择${title}',
            slotName: 'action',
            defaultValue: '',
          },
        ],
      },
      oldGoodsId: '',
      selectIndex: 0,
      selectColumns: [
        {
          title: '物品编号',
          width: 180,
          ellipsis: true,
          dataIndex: 'goodsCode',
          searchKey: 'goodsCode',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsCode',
          },
        },
        {
          title: '物品名称',
          width: 180,
          ellipsis: true,
          dataIndex: 'goodsName',
          searchKey: 'goodsName',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsName',
          },
        },
        {
          title: '规格',
          width: 100,
          ellipsis: true,
          dataIndex: 'spec',
          searchKey: 'spec',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'spec',
          },
        },
        {
          title: '物品类型',
          width: 100,
          ellipsis: true,
          dataIndex: 'typeText',
          searchKey: 'type',
          type: 'select',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'typeText',
          },
        },
        {
          title: '物品分类',
          width: 100,
          ellipsis: true,
          dataIndex: 'categoryText',
          searchKey: 'category',
          type: 'tree',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'categoryText',
          },
        },
      ],
      bomIndex: 0,
      bomColumns: [
        {
          title: '物料编号',
          align: 'center',
          dataIndex: 'goodsCode',
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'goodsName',
        },
        {
          title: '规格',
          align: 'center',
          dataIndex: 'spec',
        },
      ],
      goodsId: '',
      goodsName: '',
      bomProps: {},
      bomForm: {},
      filterForm: {},
      queryId: ''
    }
  },
  components: {
    FileUpload,
    crumbs,
    JEditableTable,
    goodsTableSelect,
  },
  methods: {
    // 重置物料
    searchResetGoods() {
      this.filterForm = {}
      this.$refs.goodsTableSelect.searchReset()
    },
    // 筛选物料
    searchGoods() {
      this.$refs.goodsTableSelect.searchQuery(this.filterForm)
    },
    // 重置子物料筛选
    searchResetBom() {
      this.bomForm = {}
      this.$refs.bomTableSelect.searchReset()
    },
    // 筛选子物料
    searchBom() {
      this.$refs.bomTableSelect.searchQuery(this.bomForm)
    },
    // 点击选择商品下拉框，弹出选择组件
    showSelect() {
      let par = {
        list: '/wms/goods/getAllGoodsBaseInfo',
        visible: true, //弹窗开启
        title: '物料', //标题名称
        multi: false, //是否多选
        columns: this.selectColumns, //表格配置
        value: this.goodsId || '', //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.goodsName || '', //回显的中文，如：'张三'
        textKey: 'goodsName', //回显的中文key
      }
      this.$refs.goodsTableSelect.getInit(par)
    },
    // 选择商品回调
    getSelectValue(id, text, item) {
      this.selectIndex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      if (!id) {
        this.selectChange()
        return
      }
      this.selectGood(id, item[0])
    },

    // 点击选择子物料下拉框，弹出选择组件
    showBomSelect(p) {
      this.bomProps = p
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [this.bomProps.rowId] }).values[0]
      let par = {
        list: '/wms/goods/getAllGoodsBaseInfo',
        visible: true, //弹窗开启
        title: '子物料', //标题名称
        multi: false, //是否多选
        columns: this.selectColumns, //表格配置
        value: tableValue.goodsId || '', //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: tableValue.goodsName || '', //回显的中文，如：'张三'
        textKey: 'goodsName', //回显的中文key
      }
      this.$refs.bomTableSelect.getInit(par)
    },
    // 选择子物料回调
    getSelectBomValue(id, text, item, rowId) {
      this.selectIndex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      if (!id) {
        this.$refs.goodsTable.setValues([
          {
            rowKey: rowId, // 行的id
            values: {
              // 在这里 values 中的 goodsId 是你 columns 中配置的 key
              goodsId: '',
              goodsName: '',
              goodsCode: '',
              basicUnit: '',
              unit: '',
              addByTask: '',
              unitList: '',
              spec: '',
              typeText: '',
              basicUnitText: '',
            },
          },
        ])
        return
      }
      this.$refs.goodsTable.setValues([
        {
          rowKey: this.bomProps.rowId, // 行的id
          values: {
            // 在这里 values 中的 goodsId 是你 columns 中配置的 key
            goodsId: id,
            goodsName: text,
            goodsCode: item[0].goodsCode,
            spec: item[0].spec,
          },
        },
      ])
      this.setBomInfo(id, item[0])
      console.log(id, text, item, this.bomProps.rowId, '列表选择的数据')
    },
    // 根据选择的子物料带出其他子物料信息并填充
    setBomInfo(value, goodSelectItem) {
      if (!value) {
        this.$refs.goodsTable.setValues([
          {
            rowKey: this.bomProps.rowId, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              spec: '-',
              typeText: '-',
              basicUnitText: '-',
            },
          },
        ])
        return
      }
      // var goodSelectItem = this.goodsTable.columns[0].options.find((item) => item.value === value)
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false }).values
      var nowValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [this.bomProps.rowId] }).values[0]
      console.log('goodSelectItemgoodSelectItemtableValue', nowValue)
      var newArr = []
      var checkParameter = { goodsId: value }
      if (this.isEdit) {
        checkParameter.id = nowValue.id
        checkParameter.bomId = this.queryId
      }
      API.checkDetailByGoodsId(checkParameter).then((res) => {
        if (res.code == 200) {
          tableValue.forEach((v) => {
            if (v.goodsId) {
              newArr.push(v.goodsId)
            }
          })
          var newArrLen = [...new Set(newArr)].length
          var oldArrLen = newArr.length
          if (newArrLen < oldArrLen) {
            this.$refs.goodsTable.removeRows(this.bomProps.rowId)
            this.$antdMessage.warning('该物料已存在，请直接修改数据')
            return
          }
          this.$refs.goodsTable.setValues([
            {
              rowKey: this.bomProps.rowId, // 行的id
              values: {
                // 在这里 values 中的 specifications 是你 columns 中配置的 key
                spec: goodSelectItem.spec || '-',
                typeText: goodSelectItem.typeText || '-',
                basicUnitText: goodSelectItem.basicUnitText || '-',
              },
            },
          ])
        } else {
          this.$antdMessage.error(res.message)
          this.$refs.goodsTable.setValues([
            {
              rowKey: this.bomProps.rowId, // 行的id
              values: {
                // 在这里 values 中的 specifications 是你 columns 中配置的 key
                goodsId: '',
                spec: '-',
                typeText: '-',
                basicUnitText: '-',
              },
            },
          ])
        }
      })
    },
    // 子物料选择框回显值
    BomNameText(p) {
      var item = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [p.rowId] }).values[0]
      console.log('itemssssss:', item)
      return `${item.goodsCode ? item.goodsCode + ' | ' : ''}${item.goodsName ? item.goodsName + ' | ' : ''}${
        item.spec ? item.spec : ''
      }`
    },
    // 下拉搜索
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleDeleteGood(p) {
      this.$refs.goodsTable.removeRows(p.rowId)
    },
    valueChange(type) {
      // ['number', () => {
      //   this.$refs.goodsTable.setValues([
      //     {
      //       rowKey: type.row.id, // 行的id
      //       values: { // 在这里 values 中的 amount 是你 columns 中配置的 key
      //         'number': integerNum(type.value),
      //         'amount': this.multiplication(type.value, type.row.price || 0)
      //       }
      //     }
      //   ])
      //   this.sum(this.$refs.goodsTable.getValuesSync().values)
      // }],
      // console.log(type)
      if (type.column.key == 'basicUseLevel') {
        this.$refs.goodsTable.setValues([
          {
            rowKey: type.row.id, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              basicUseLevel: fourFloatNum(type.value),
            },
          },
        ])
      }
      if (type.column.key == 'loss') {
        this.$refs.goodsTable.setValues([
          {
            rowKey: type.row.id, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              loss: fourFloatNum(type.value),
            },
          },
        ])
      }
      // if (type.column.key == 'goodsId') {
      //   if (!type.value) {
      //     this.$refs.goodsTable.setValues([
      //       {
      //         rowKey: type.row.id, // 行的id
      //         values: { // 在这里 values 中的 specifications 是你 columns 中配置的 key
      //           'spec': '-',
      //           'typeText': '-',
      //           'basicUnitText': '-',
      //         }
      //       }
      //     ])
      //     return
      //   }
      //   var goodSelectItem = this.goodsTable.columns[0].options.find((item) => item.value === type.value)
      //   var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false }).values
      //   var nowValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [type.row.id] }).values[0]
      //   console.log('goodSelectItemgoodSelectItemtableValue',nowValue)
      //   var newArr = []
      //   var checkParameter = {goodsId: type.value}
      //   if (this.isEdit) {
      //     checkParameter.id = nowValue.id
      //     checkParameter.bomId = this.$route.query.id
      //   }
      //   API.checkDetailByGoodsId(checkParameter).then(res => {
      //     if (res.code == 200) {
      //       tableValue.forEach(v => {
      //         newArr.push(v.goodsId)
      //       })
      //       var newArrLen = [...new Set(newArr)].length
      //       var oldArrLen = tableValue.length
      //       if (newArrLen < oldArrLen) {
      //         this.$refs.goodsTable.removeRows(type.row.id)
      //         this.$antdMessage.warning('该物料已存在，请直接修改数据')
      //         return
      //       }
      //       this.$refs.goodsTable.setValues([
      //         {
      //           rowKey: type.row.id, // 行的id
      //           values: { // 在这里 values 中的 specifications 是你 columns 中配置的 key
      //             'spec': goodSelectItem.spec || '-',
      //             'typeText': goodSelectItem.typeText || '-',
      //             'basicUnitText': goodSelectItem.basicUnitText || '-',
      //           }
      //         }
      //       ])
      //     } else {
      //       this.$antdMessage.error(res.message)
      //       this.$refs.goodsTable.setValues([
      //         {
      //           rowKey: type.row.id, // 行的id
      //           values: { // 在这里 values 中的 specifications 是你 columns 中配置的 key
      //             'goodsId': '',
      //             'spec': '-',
      //             'typeText': '-',
      //             'basicUnitText': '-',
      //           }
      //         }
      //       ])
      //     }
      //   })
      // }
    },
    /* 获取物料下拉数据 */
    getGoods() {
      API.getAllGoodsBaseInfo({ pageSize: 9999, pageNo: 1 }).then((res) => {
        if (res.code == 200) {
          if (res.result.records) {
            this.goodSelectList = res.result.records
            this.goodsTable.columns[0].options = []
            res.result.records.forEach((item) => {
              // item.title = item.goodsName
              item.title = item.goodsCode + '-' + item.goodsName
              item.text = item.goodsCode + '-' + item.goodsName
              item.value = item.id
              this.goodsTable.columns[0].options.push(item)
            })
          }
          // this.goodsTable.columns[0].options = res.result.records || []
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    /* 选择物料后查询带出物料信息 */
    selectChange(v) {
      if (!v) {
        this.form.setFieldsValue({
          spec: '-',
          basicUnitText: '-',
          typeText: '-',
          categoryText: '-',
          goodsId: '',
        })
        this.goodsId = ''
        this.goodsName = ''
        return
      }
    },
    selectGood(v, good) {
      // let good = this.goodSelectList.find(item => item.id == v)
      var checkParameter = { goodsId: good.id }
      if (this.isEdit) {
        checkParameter.id = this.queryId
      }
      API.checkInfoByGoodsId(checkParameter).then((res) => {
        if (res.code == 200) {
          this.oldGoodsId = v
          this.form.setFieldsValue({
            spec: good.spec,
            basicUnitText: good.basicUnitText,
            typeText: good.typeText,
            categoryText: good.categoryText,
            goodsId: v,
          })
          this.goodsId = v
          this.goodsName = good.goodsName
        } else {
          this.$antdMessage.error(res.message)
          this.form.setFieldsValue({
            spec: this.isEdit ? good.spec : '-',
            basicUnitText: this.isEdit ? good.basicUnitText : '-',
            typeText: this.isEdit ? good.typeText : '-',
            categoryText: this.isEdit ? good.categoryText : '-',
            goodsId: this.isEdit ? this.oldGoodsId : '',
          })
          this.goodsId = this.isEdit ? v : ''
          this.goodsName = this.isEdit ? good.goodsName : ''
        }
      })
      console.log(good)
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取编辑详情 */
    initForm(query) {
      Object.assign(this.$data, this.$options.data.call(this));
      this.jkeForm.visible = true
      let id = query.id
      this.queryId = id
      if (id) {
        this.jkeForm.title = '编辑BOM'
        this.submitApi = API.messBomInfoEdit
        this.isEdit = true
        API.messBomInfoQueryById(id).then((res) => {
          if (res.code == 200) {
            this.$nextTick(() => {
              this.form.setFieldsValue(res.result)
              this.goodsName = res.result.goodsName
              this.attachment = res.result.attachment
              this.oldGoodsId = res.result.goodsId
              this.getBomList()
            })
          }
        })
      } else {
        this.jkeForm.title = '新建BOM'
      }
    },
    /* 获取子物料详情 */
    getBomList() {
      let parameter = {
        bomId: this.queryId,
        pageNo: 1,
        pageSize: 999,
      }
      API.queryBomListByBomId(parameter).then((res) => {
        if (res.code == 200) {
          let list = res.result.records
          list.forEach((item) => {
            item.basicUnitText = item.goodsBasicUnitText
            item.typeText = item.goodsTypeName
            item.spec = item.goodSpec
          })
          this.goodsTable.dataSource = list
        }
      })
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    handleSubmit() {
      let errArr = []
      let parameters = {}
      let { error, values } = this.$refs.goodsTable.getValuesSync({ validate: true })
      if (error === 0) {
        console.log('表单验证通过，数据：', values)
      } else {
        errArr.push(false)
        console.log('未通过表单验证，数据：', values)
      }
      this.form.validateFields((err, formValues) => {
        if (!err) {
          parameters = { ...formValues, attachment: this.attachment }
          if (this.isEdit) {
            parameters.id = this.queryId
          }
          parameters.goodsId = this.goodsId
        } else {
          errArr.push(false)
        }
      })
      if (errArr.length == 0) {
        let messBomDetails = values.map((g, i) => {
          return {
            goodsId: g.goodsId,
            basicUseLevel: g.basicUseLevel,
            loss: g.loss,
            serialNo: i + 1,
          }
        })
        parameters.messBomDetails = messBomDetails
        parameters.goodsId = this.oldGoodsId
        console.log(parameters)
        this.loadingSubmit = true
        this.submitApi(parameters).then((res) => {
          this.loadingSubmit = false
          if (res.code == 200) {
            let subMsg = this.isEdit ? 'BOM编辑成功！' : 'BOM创建成功！'
            this.$antdMessage.success(subMsg)
            this.$emit('refresh')
            this.goBack()
          } else {
            this.$antdMessage.error(res.message)
          }
        })
      }
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
/deep/.ant-form-vertical {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}
</style>
